package com.jh3502.vivo.utils;

import android.app.Activity;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;

import java.util.LinkedList;
import java.util.List;

/**
 * @author harisucici
 * 一次性关闭
 */
public class ActivityTracker {
    @NonNull
    private static List<Activity> ACTIVITIES = new LinkedList<>();
    private static ActivityTracker activityTracker;

    public static synchronized ActivityTracker getInstance() {
        if (activityTracker == null) {
            activityTracker = new ActivityTracker();
        }
        return activityTracker;
    }

    public void onCreate(@Nullable Activity activity) {
        if (activity == null) {
            throw new IllegalArgumentException("Activity instance is null");
        }
        ACTIVITIES.add(activity);
        Log.i("ACTIVITIES_add", ACTIVITIES.size() + "");
    }

    public void onDestory(@Nullable Activity activity) {
        if (activity != null) {
            ACTIVITIES.remove(activity);
            Log.i("ACTIVITIES_remove", ACTIVITIES.size() + "");
        }
    }

    public void finishAll() {
        for (Activity activity : ACTIVITIES) {
            if (activity.getParent() != null) {
                activity.getParent().onBackPressed();
            }

            activity.onBackPressed();
        }
        ACTIVITIES.clear();
        Log.i("ACTIVITIES_clear", ACTIVITIES.size() + "");

    }
}
